package com.qiguliuxing.dts.admin.service.excel;


import com.alibaba.fastjson.JSONObject;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.admin.web.AdminInstrumentController;
import com.qiguliuxing.dts.db.dao.GmInstrumentMapper;
import com.qiguliuxing.dts.db.domain.GmInstrument;
/*import com.why.MyProject.common.MyException;
import com.why.MyProject.entity.instrument;
import com.why.MyProject.mapper.UserMapper;*/
import com.qiguliuxing.dts.db.service.GmInstrumentService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//import static jdk.nashorn.internal.runtime.regexp.joni.Syntax.Java;

@Service
@Transactional(readOnly = true)
public class TestServiceImpl implements ITestService {

    @Autowired
    private GmInstrumentService instrumentService;
    private static final Logger logger = LoggerFactory.getLogger(AdminInstrumentController.class);

    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {

        boolean notNull = false;
        List<GmInstrument> gmInstrumentsList = new ArrayList<GmInstrument>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        GmInstrument instrument;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            instrument = new GmInstrument();

            /*if( row.getCell(0).getCellType()!=CellType.STRING){
                throw new MyException("导入失败(第"+(r+1)+"行,姓名请设为文本格式)");
            }*/
            String name = row.getCell(1).getStringCellValue();

            if(name == null || name.isEmpty()){
                throw new MyException("导入失败(第"+(r+1)+"行,名称未填写)");
            }

            row.getCell(2).setCellType(CellType.STRING);
            String manufactory = row.getCell(2).getStringCellValue();
            if(manufactory==null || manufactory.isEmpty()){
                throw new MyException("导入失败(第"+(r+1)+"行,生产厂家)");
            }
            String instrumentModel = row.getCell(3).getStringCellValue();
            String instrumentNumber = row.getCell(4).getStringCellValue();
            String userDepartment = row.getCell(5).getStringCellValue();
            String verficationUnit = row.getCell(6).getStringCellValue();
       /*     String verfyDate = row.getCell(7).getStringCellValue();*/
            String vertificationCycle = row.getCell(8).getStringCellValue();
            String periodValidity = row.getCell(9).getStringCellValue(); /*有效期*/
            Integer overdue=Integer.parseInt(row.getCell(10).getStringCellValue());
            if(manufactory==null){
                throw new MyException("导入失败(第"+(r+1)+"行,不存在此单位或单位未填写)");
            }

            LocalDate verfyDate;
            if(row.getCell(7).getCellType() != CellType.NUMERIC){
                throw new MyException("导入失败(第"+(r+1)+"行,检定日期格式不正确或未填写)");
            }else{
                verfyDate = LocalDate.parse(row.getCell(7).getStringCellValue() , DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }

      /*      String des = row.getCell(4).getStringCellValue();*/

            instrument.setInstrumentName(name);
            instrument.setManufacturer(manufactory);
            instrument.setInstrumentNumber(instrumentNumber);
            instrument.setUserDepartments(userDepartment);
            instrument.setVerficationUnit(verficationUnit);
            instrument.setVerfyDate(verfyDate);
            instrument.setMeasuringRange(vertificationCycle);
            instrument.setInstrumentModel(instrumentModel);
            instrument.setOverdue(overdue);
            gmInstrumentsList.add(instrument);
        }
        for (GmInstrument instrument1 : gmInstrumentsList) {
            String name = instrument1.getInstrumentName();

       /*     if (cnt == 0) {
                userMapper.addUser(userResord);*/
                System.out.println(" 插入 "+name);
            logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 器材管理->器材列表->新增,请求参数:{}", JSONObject.toJSONString(instrument1));
          /*  } else {*/
           /*     userMapper.updateUserByName(userResord);
                System.out.println(" 更新 "+userResord);
            }*/
        }
        return notNull;
    }
}
